package com.bosssoft.ct.springcloud.filter;

/**
 * 网关鉴权拦截器
 *
 * @author ChenTong
 * @version 1.0
 * @date 2020/6/23 21:23
 * @copyright
 * @modified
 * @see
 * @since
 **/

import com.bosssoft.ct.springcloud.utils.token.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthenticationGatewayFilter implements GlobalFilter, Ordered {
    private static final String AUTH_HEADER = "Authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();


        String token = "";

        String auth = request.getHeaders().getFirst(AUTH_HEADER);

        log.info("global filter auth {}", auth);

        if(auth!=null&&auth.contains("Bearer ")){
            token += auth.split(" ")[1];
        }else {
            token = auth;
        }
        //执行验证
        if(token==null || token.equals("")){
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//给人家一个回应
            return exchange.getResponse().setComplete();
        }else{
            //获取token中的用户信息
            Claims claims;
            //验证token
            claims = TokenUtil.parseJWT(token);
            //获取token中的用户名
            String username = claims.getId();
            //在请求中加入用户信息方便获取
            log.info("从token中获取用户名-{}", username);

            ServerHttpRequest host = request.mutate().headers(httpHeaders ->
                httpHeaders.add("username", username)
            ).build();
            ServerWebExchange build = exchange.mutate().request(host).build();

            return chain.filter(build);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
